import React, { useEffect } from 'react'
import s from './style.module.less'
import Header from './components/Header'
import BillItem from './components/BillItem/BillItem'
import { get, REFRESH_STATE, LOAD_STATE } from '@/utils'
import { useState } from 'react'
import dayjs from 'dayjs'
import { Pull } from 'zarm'

export default function Home() {
  const [currentTime, setCurrentTime] = useState(dayjs().format('YYYY-MM')); // 账单时间
  const [currentSelect, setCurrentSelect] = useState({}); // 账单类型
  const [page, setPage] = useState(1); // 分页
  const [list, setList] = useState([]); // 账单列表
  const [totalExpense, setTotalExpense] = useState(0); // 总支出
  const [totalIncome, setTotalIncome] = useState(0); // 总收入
  const [totalPage, setTotalPage] = useState(0); // 总页数
  const [refreshing, setRefreshing] = useState(REFRESH_STATE.normal) // 下拉刷新的状态
  const [loading, setLoading] = useState(LOAD_STATE.normal) // 上拉加载的状态


  useEffect(() => {
    getBillList()
  }, [])

  const getBillList = async () => {
    const { data } = await get(`/api/bill/list?date=${currentTime}&type_id=${currentSelect.id || 'all'}&page=${page}&page_size=5`)
    console.log(data);

    setTotalExpense(data.totalExpense)
    setTotalIncome(data.totalIncome)
    setTotalPage(data.totalPage)

    setList(data.list)
  }

  // 下拉刷新
  const refreshData = async () => {
    setRefreshing(REFRESH_STATE.loading)
    if (page !== 1) {
      setPage(1)
    } else {
      await getBillList()
      setRefreshing(REFRESH_STATE.success)
    }
  }
  // 上拉加载
  const loadData = () => {
    setLoading(LOAD_STATE.loading)
    console.log(11111);
    if (page < totalPage) {
      console.log(12312312);
      setLoading(LOAD_STATE.loading)
    }
  }

  return (
    <div className={s.home}>
      <Header totalExpense={totalExpense} totalIncome={totalIncome} />
      <div className={s.contentWrap}>
        {
          list.length ? <Pull
            animationDuration={200}
            stayTime={1000}
            refresh={{
              state: refreshing,
              handler: refreshData
            }}
            load={{
              state: loading,
              distance: 0,
              handler: loadData
            }}
          >
            {
              list.map((item, index) => <BillItem key={index} bill={item} />)
            }
          </Pull> : <></>
        }
      </div>
    </div>
  );
}
